package com.ssn.observer.stock;

import java.util.ArrayList;

public class Stock implements Subject{
    private String name;
    private double old;
    private double now;
    private ArrayList<Observer> observers = new ArrayList<>();
    Stock(String name){
        old = 200;
        now = 200;
        this.name = name;
    }
    public void setNow(double now) {
        System.out.println("原价格：" + old);
        System.out.println("新价格：" + now);
        this.now = now;
        if (Math.abs((now - old) / old) > 0.05){
            notifyObserver();
        }
        this.old = now;
    }
    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void detach(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObserver() {
        for (Observer observer: observers) {
            observer.update(getMessage());
        }
    }
    public String getMessage() {
        return "股票 " + this.name + " 涨跌超过5%，现价为：" + now;
    }
}
